import { Outlet, redirect, useLocation, type RouteObject } from "react-router-dom";
import { useEffect, useState } from "react";
import { getMatches } from "./index";
import { store } from "@/store";
import { getRoutesByRole } from "@/api/modules/menu";
import { setDynamicMenu } from "@/store/menu";
import Loading from "@/components/public/loading/Index";

const AuthRoute = () => {
  const [loading, setLoading] = useState(true);
  const dispatch = store.dispatch;
  const location = useLocation();
  const token = localStorage.getItem("token"); // 登录凭证
  // 前缀匹配白名单：以这些路径开头的路由不需要登录验证
  const prefixWhitelist: string[] = ["/error"];
  // 全匹配白名单：这些路由完全匹配时不需要登录验证
  const fullMatchWhitelist: string[] = ["/login"];

  useEffect(() => {
    // 检查路由是否在白名单中
    const isInFullMatchWhitelist = fullMatchWhitelist.includes(location.pathname);
    const isInPrefixWhitelist = prefixWhitelist.some((prefix) => location.pathname.startsWith(prefix));
    // 白名单放行
    if (isInFullMatchWhitelist || isInPrefixWhitelist) {
      setLoading(false);
      return;
    } else if (!token) {
      // 没登录 → 跳转登录页，并带上 redirect
      setLoading(false);
      redirect("/login?redirect=" + location.pathname);
      return;
    }

    // 获取动态菜单
    const state = store.getState();
    let dynamicMenu = state.menu.dynamicMenu;
    const getRoutes = async () => {
      const res = await getRoutesByRole();
      dispatch(setDynamicMenu(res.data));
      setPageTitle();
      setLoading(false);
    };
    if (dynamicMenu.length === 0) {
      setLoading(true);
      getRoutes();
    } else {
      setLoading(false);
    }

    const setPageTitle = () => {
      // 页面设置名称;
      const routeInfo = getMatches(location.pathname);
      const route = routeInfo?.at(-1)?.route as RouteObject;
      if (route && route?.handle?.meta?.title) {
        const title = route.handle.meta.title;
        document.title = title ? `${title} - 管理系统` : "管理系统";
      }
    };
    setPageTitle();
  }, [location]);
  return loading ? <Loading /> : <Outlet />;
};

export default AuthRoute;
